<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item v-hasPermi="['nongjt:certificate:edit']" label="账号"  prop="mobilePhone">
        <el-input
          v-model="queryParams.user.mobilePhone"
          placeholder="请输入账号"
          clearable
          class="w_200"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item v-hasPermi="['nongjt:certificate:edit']" label="开具时间" prop="startToEndTime">
        <el-date-picker
          v-model="startToEndTime"
          value-format="yyyy-MM-dd"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="w_200"
          size="mini"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item v-hasPermi="['nongjt:certificate:edit']" label="主体名称" prop="companyName">
        <el-input
          v-model="queryParams.user.companyName"
          placeholder="请输入主体名称"
          clearable
          class="w_200"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          class="w_200"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--省市区级联组件-->
      <el-form-item v-hasPermi="['nongjt:certificate:edit']" label="省" prop="province">
        <el-select v-model='queryParams.user.province' filterable placeholder="请选择省" clearable   class="w_200">
          <el-option v-for='(temp,index) in mixinsProvinceList' :value="temp.name" :key='index' :label="temp.name"
                     @click.native='mixinsProvinceChange(temp.code)'/>
        </el-select>
      </el-form-item>
      <el-form-item v-hasPermi="['nongjt:certificate:edit']" label="市" prop="city">
        <el-select v-model='queryParams.user.city' filterable placeholder="请选择市(请先选择省)" clearable   class="w_200">
          <el-option v-for='(temp,index) in mixinsCityList' :value="temp.name" :key='index' :label="temp.name"
                     @click.native='mixinsCityChange(temp.code)'/>
        </el-select>
      </el-form-item>
      <el-form-item v-hasPermi="['nongjt:certificate:edit']" label="区" prop="area">
        <el-select v-model='queryParams.user.area' filterable placeholder="请选择区/县(请先选择市)" clearable   class="w_200">
          <el-option v-for='(temp,index) in mixinsAreaList' :value="temp.name" :key='index' :label="temp.name"  @click.native='mixinsAreaChange(temp.code)'  />
        </el-select>
      </el-form-item>
      <el-form-item v-hasPermi="['nongjt:certificate:edit']" label="街道" prop="country" >
        <el-select v-model='queryParams.user.country' filterable placeholder="请选择街道(请先选择区/县)" clearable   class="w_200">
          <el-option v-for='(temp,index) in mixinsStreetList' :value="temp.name" :key='index' :label="temp.name"/>
        </el-select>
      </el-form-item>

      <el-form-item v-hasPermi="['nongjt:certificate:edit']" label="数据来源" prop="sourceType">
        <el-select v-model="queryParams.sourceType" class="w_200" placeholder="请选择数据来源">
          <el-option
            v-for="dict in dict.type.source_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-hasPermi="['nongjt:certificate:edit']" label="自助服务点" prop="unit">
        <el-select v-model='queryParams.serialCode' class="w_200" :allowClear='true' placeholder='请选择自助服务点'>
          <el-option :label="temp.posName" :value='temp.serialCode' v-for='temp in posList' :key="temp.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="检验机构" prop="testBy">
        <el-input
          v-model="queryParams.testBy"
          placeholder="请输入检验机构"
          clearable
          size="small"
          class="w_200"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合格方式" prop="userSignature">
        <el-select v-model="queryParams.testType" class="w_200" placeholder="请选择合格方式">
          <el-option
            v-for="dict in dict.type.test_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="合格证编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入合格证编号"
          clearable
          class="w_200"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="被扫查验" prop="scanNum">
        <el-select  v-model="queryParams.scanNumFlag" class="w_200" placeholder="请选择是否被扫查验">
          <el-option :value='1'  label="是"></el-option>
          <el-option :value='0' label="否"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label=" ">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">-->
      <!--<el-button-->
      <!--type="primary"-->
      <!--plain-->
      <!--icon="el-icon-plus"-->
      <!--size="mini"-->
      <!--@click="handleAdd"-->
      <!--v-hasPermi="['nongjt:certificate:add']"-->
      <!--&gt;新增</el-button>-->
      <!--</el-col>-->
      <!--<el-col :span="1.5">-->
      <!--<el-button-->
      <!--type="success"-->
      <!--plain-->
      <!--icon="el-icon-edit"-->
      <!--size="mini"-->
      <!--:disabled="single"-->
      <!--@click="handleUpdate"-->
      <!--v-hasPermi="['nongjt:certificate:edit']"-->
      <!--&gt;修改</el-button>-->
      <!--</el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['nongjt:certificate:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['nongjt:certificate:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="certificateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账号" align="center" width="110">
        <template scope="scope">
          <span>{{ scope.row.userPerfect.mobilePhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产主体" align="center" width="120" :show-overflow-tooltip="true">
        <template scope="scope">
          {{ scope.row.userPerfect.companyName }}
        </template>
      </el-table-column>
      <el-table-column label="法人姓名" align="center">
        <template scope="scope">
          {{ scope.row.userPerfect.legalPersonName }}
        </template>
      </el-table-column>
      <el-table-column label="省" align="center">
        <template scope="scope">
          {{ scope.row.userPerfect.province }}
        </template>
      </el-table-column>
      <el-table-column label="市" align="center">
        <template scope="scope">
          {{ scope.row.userPerfect.city }}
        </template>
      </el-table-column>
      <el-table-column label="区/县" align="center">
        <template scope="scope">
          {{ scope.row.userPerfect.area }}
        </template>
      </el-table-column>
      <el-table-column label="镇/乡" align="center" width="100">
        <template scope="scope">
          {{ scope.row.userPerfect.country }}
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" width="120" :show-overflow-tooltip="true" >
        <template scope="scope">
          {{ scope.row.userPerfect.detailAddress }}
        </template>
      </el-table-column>
      <el-table-column label="生产地址" align="center" prop="produceAddress" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="食用产品名称" align="center" prop="productName" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="重量（数量）" align="center" prop="productWeight" width="100" />

      <el-table-column prop="unit" label="单位" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.unit_type" :value="scope.row.unit"/>
        </template>
      </el-table-column>

      <el-table-column label="合格方式" align="center" prop="testType" ></el-table-column>
      <!--<template slot-scope="scope">-->
      <!--<dict-tag :options="testTypes" :value="scope.row.testType"/>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="检验机构" align="center" prop="testBy" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="检测报告" align="center" prop="testReport">
        <template scope="scope">
          <el-popover
            placement="right"
            width="200"
            trigger="hover">
            <el-image :src="getView(scope.row.userPerfect.testReport)" />
            <el-image slot="reference" :src="getView(scope.row.userPerfect.testReport)" style="max-height: 50px;max-width: 150px"/>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="开具日期" align="center" prop="createTime" width="160" />
      <el-table-column label="合格证编号" align="center" prop="code" width="180" />
      <el-table-column label="打印次数" align="center" prop="printNumber" />
      <el-table-column label="扫描次数" align="center" prop="scanNum" />
      <el-table-column label="数据来源" align="center" prop="sourceType" width="100" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.source_type" :value="scope.row.sourceType"/>
        </template>
      </el-table-column>
      <template v-hasPermi="['nongjt:certificate:edit']">
        <el-table-column  label="操作" fixed="right" align="center" width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['nongjt:certificate:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['nongjt:certificate:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </template>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合格证管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="40%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="账号" prop="mobilePhone">
          <el-input v-model="form.mobilePhone" placeholder="请输入账号" disabled/>
        </el-form-item>
        <el-form-item label="生产主体" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入生产主体" disabled/>
        </el-form-item>
        <el-form-item label="法人" prop="legalPersonName">
          <el-input v-model=" form.legalPersonName" placeholder="请输入法人" disabled/>
        </el-form-item>
        <el-form-item label="企业地址" prop="address">
          <el-input v-model="address" placeholder="请输入企业地址" disabled/>
        </el-form-item>
        <el-form-item label="生产地址" prop="produceAddress">
          <el-input v-model="form.produceAddress" placeholder="请输入生产地址"/>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称"/>
        </el-form-item>
        <el-form-item label="产品重量" prop="productWeight">
          <el-input v-model="form.productWeight" placeholder="请输入产品重量" >
            <el-select v-model="form.unit" slot="append">
              <el-option
                v-for="dict in dict.type.unit_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item label="合格方式" prop="testType">
          <el-select v-model="form.testType" placeholder="请选择合格方式" disabled style="width: 100%">
            <el-option
              v-for="dict in dict.type.test_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开具时间" prop="code">
          <el-date-picker
            v-model="form.createTime"
            type="datetime"
            placeholder="选择日期时间" disabled style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合格证编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入合格证编号" disabled />
        </el-form-item>
        <el-form-item label="打印次数" prop="printNumber">
          <el-input-number v-model="form.printNumber" placeholder="请输入打印次数" style="width: 100%"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { exportAll,listCertificate, getCertificate, delCertificate, addCertificate, updateCertificate,queryExportProgress,exprotAllCertificate,download } from "@/api/certificate/certificate";
import {PublicMixins} from "@/mixins/PublicMixins";
import {getActionSimple} from "@/utils/axiosUtils";
import {AreaMixins} from "@/mixins/AreaMixins";
import {mapGetters} from "vuex";
import {Loading} from "element-ui";


export default {
  name: "NjtCertificateList",
  dicts: ['unit_type', 'source_type','test_type'],
  mixins:[PublicMixins,AreaMixins],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合格证管理表格数据
      certificateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        user:{
          mobilePhone:null,
          companyName:null,
          province:null,
          city:null,
          area:null,
          country:null,
        },
        userPerfectString:null,
        productName: null,
        testType: null,
        testBy: null,
        code: null,
        startTime:null,
        endTime:null,
        serialCode:null,
        scanNumFlag:null,
        sourceType:null
      },
      startToEndTime:null,
      //自主服务点
      posList:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: "主体名称不能为空", trigger: "blur" }
        ],
        productAddress: [
          { required: true, message: "产品地址不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        productWeight: [
          { required: true, message: "产品重量不能为空", trigger: "change" }
        ],
      },
      url: {
        userStreetList: '/certificate/statistics/getUserStreetAll',
        getYtjPosList:'/certificate/pos/allList'
      },
      address:null,
      userPerfect:{
        mobilePhone:null,
        companyName:null,
        legalPersonName:null,
        province:null,
        city:null,
        area:null,
        country:null,
        detailAddress:null
      },
    };
  },
  created() {
    //初始化url中的查询条件
    this.initUrlParam()
    this.queryParams.userPerfectString=JSON.stringify(this.queryParams.user)
    this.getList();

    //管理员才去访问
    if (this.roles.includes('admin')){
      this.getPosList()
    }

  },
  methods: {
    initUrlParam(){
      let {mobilePhone,country,area,dateBegin,dateEnd,companyName,productName} = this.$route.query
      if (mobilePhone) {
        // 如果路由里有查询参数，则设置默认查询条件
        this.queryParams.user.mobilePhone = mobilePhone
      }
      if (country) {
        // 如果路由里有查询参数，则设置默认查询条件
        this.queryParams.user.country = country
      }
      if (area) {
        // 如果路由里有查询参数，则设置默认查询条件
        this.queryParams.user.area = area
      }
      if(dateBegin && dateEnd){
        this.startToEndTime=[dateBegin,dateEnd]
      }
      if(companyName){
        this.queryParams.user.companyName = companyName
      }
      if(productName){
        this.queryParams.productName = productName
      }
    },
    /** 查询合格证管理列表 */
    getList() {
      this.loading = true;
      listCertificate(this.queryParams).then(response => {
        this.certificateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userPerfectString:null,
        produceAddress: null,
        productName: null,
        productWeight: null,
        unit: null,
        testType: null,
        teatBy:null,
        testReport: null,
        code: null,
        printNumber: null,
        scanNum: null,
        sourceType:null,
        createTime:null
      };
      this.resetForm("form");
    },
    //获取自助服务点列表
    async getPosList(){
      this.posList = await getActionSimple(this.url.getYtjPosList,this.queryParams)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      let{mobilePhone,province,city,area,country,companyName}=this.queryParams.user
      if (mobilePhone || province|| city || area || country || companyName) {
        this.queryParams.userPerfectString=JSON.stringify(this.queryParams.user)
      }
      if (this.startToEndTime) {
        let [startTime,endTime] = this.startToEndTime
        this.queryParams.startTime = startTime
        this.queryParams.endTime = endTime
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {}
      this.queryParams.user={}
      this.startToEndTime=[]
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合格证管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCertificate(id).then(response => {
        this.form = response.data;
        const temp = this.form.userPerfect
        this.form=Object.assign({},this.form.userPerfect,this.form)
        this.address = temp.province + temp.city + temp.area + temp.country + temp.detailAddress
        this.open = true;
        this.title = "修改合格证管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCertificate(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCertificate(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除合格证管理编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delCertificate(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出所有合格证管理数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        let text = "导出数据中，请勿刷新页面";
        let downloadLoadingInstance = Loading.service({ text: text, spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
        //请求服务器创建临时文件
        exportAll().then(resp=>{
          let tempFile = resp.data;
          //定时(每隔1秒)查询临时文件创建进度
          let task = setInterval(()=>{
              //查询进度
              queryExportProgress().then(resp=>{
                downloadLoadingInstance.setText(`创建进度为${resp.data}`);
                //判断是否创建完成
                if (resp.data >= 100) {
                  //取消定时任务
                  clearInterval(task);
                  //下载文件
                  this.download("/certificate/certificate/download/"+tempFile, {}, `合格证打印数据.xlsx`)
                  this.exportLoading = false;
                }
              })
            },1000)
        }).catch(err=>{
          downloadLoadingInstance.close();
        });
      }).catch(() => {
        this.exportLoading = false;
      });
    }
  },
  computed: {
    ...mapGetters(['roles']),
  }
};
</script>

<style lang="scss" scoped>
.w_200 {
  width: 200px;
}
</style>
